import java.io.*;

import javax.swing.*;


public class YTSubCount
{
	public static void main(String args[]) throws IOException
	{
		int n = -1;
		do
		{
			try
			{
				n = JOptionPane.showConfirmDialog(null, "Is this the first file?", "File option", JOptionPane.YES_NO_OPTION);
			}
			catch(Exception e)
			{
				
			}
		}while(n == -1);
		
		String output = "";
		String input = "";
		if(n == 0)
		{
			input = "sub1.txt";
			output = "out1.txt";
		}
		else
		{
			input = "sub2.txt";
			output = "out2.txt";
		}
		
		try
		{
			// Open the file that is the first 
			// command line parameter
			FileInputStream fstream = new FileInputStream(input);
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			//Read File Line By Line
			
			String content = "";
			boolean start = false;
			boolean end = false;
			while (((strLine = br.readLine()) != null) && !end)
			{
				if(!start && (strLine.indexOf("channel-summary-list subscribers-listing") != -1))
				{
					start = true;
				}
				if(start && (strLine.indexOf("footer-container") != -1))
				{
					end = true;
				}
				
				if(start && !end)
				{
					content += strLine;
				}
				
				// Print the content on the console
				//System.out.println (strLine.indexOf("<ul class=\"channel-summary-list subscribers-listing\">"));
			}
			
			// Create file 
			FileWriter ostream = new FileWriter(output,false);
			BufferedWriter out = new BufferedWriter(ostream);
			
			int getFirst = 0;
			int lowest = 0;
			
			while(getFirst != -1)
			{
				int getNext = content.indexOf("<a href=\"/user", getFirst);
				int dummy = content.indexOf("user", getNext);
				int startNext = content.indexOf('/', dummy) + 1;
				int endNext = content.indexOf('"', startNext);
				
				getFirst = content.indexOf("subscriber-count", endNext);
			
				if(lowest <= getNext)
				{
					lowest = getNext;
					
					out.write(content.substring(startNext, endNext) + "\n");
					System.out.println(content.substring(startNext, endNext));
				}
				else
				{
					getFirst = -1;
				}
			}
			
			//Close the input stream
			in.close();
			//Close the output stream
			out.close();
		}catch (Exception e)
		{//Catch exception if any
			JOptionPane.showMessageDialog(null,"You need to take the html source code of your subscriber page and put it into a file called '" + input + "' located right beside this program's executable.");
			System.err.println("Error: " + e.getMessage());
		}
		
		JOptionPane.showMessageDialog(null,"Done");
	}
}
